<!--  -->
<template>
  <!-- :expand-on-click-node="false" 点击后禁用掉菜单会下拉 
   :default-checked-keys="expandedKey"
   :default-expanded-keys="expandedKey"
  -->
  <div>
    <el-tree :expand-on-click-node="false" show-checkbox
     node-key="catId" draggable 
     :allow-drop="allowDrop"
     @node-drop="handleDrop"
     :default-expanded-keys="expandedKey"
      :data="menus" :props="defaultProps">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" v-if="node.level <= 2" size="mini" @click="() => append(data)">
            添加
          </el-button>

          <el-button type="text"  size="mini" @click="() => edit(data)">
            修改
          </el-button>

          <el-button type="text" v-if="node.childNodes.length == 0" size="mini" @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称" >
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" >
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" >
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  data() {
    return {
      maxLevel:0,//最大的层级
      title:"",
      disalogType:"",//edit，add
      dialogVisible: false, //展示属性默认关闭
      category:{name:"",parentCid:0,catLevel:0,showStatus:1,sort:0,catId:null,icon:"",productUnit:""},
      menus: [],
      expandedKey: [], //默认展开的节点
      defaultProps: {
        children: "children",
        label: "name",
      },
      updateNode:[],// 记录要修改的节点

    };
  },
  //创建完成
  created() {
    this.getMenus();
  },
  methods: {
    //1.获取菜单数据
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
      }).then(({ data }) => {
        console.log("成功获取到菜单数据...", data.data);
        this.menus = data.data;
      });
    },
    //2.添加菜单
    append(data) {
      //添加菜单前先质控
      // category:{name:"",parentCid:0,catLevel:0,showStatus:1,sort:0,catId:null},
      console.log(data);

      this.disalogType = "add";
      this.title="添加三级分类的信息";
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      
      this.category.name = "";
      this.category.showStatus = 1;
      this.category.sort = 0;
      this.category.productUnit = "";
      this.category.catId = null;
      this.category.icon = "";
    },

     //添加三级分类的信息
     addCategory(){
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({message:"添加成功",type:"success"})
        // 关闭对话框
        this.dialogVisible = false;
        //刷新出新的菜单
        this.getMenus();
        //设置需要默认展开的菜单
        this.expandedKey = [this.category.parentCid];
      });
    
    },

    submitData(){
      if(this.disalogType == "add"){
        this.addCategory();
      }else{
        this.editCategory();
      }
    },
    //4.修改内容
    edit(data){
      this.disalogType = "edit";
      console.log("需要修改的内容",data);
      this.title="修改三级分类的信息";
      this.dialogVisible = true;

      this.$http({
        // product/category/info/{catId}
        url:this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method:"get"
      }).then(({data})=>{
        
        console.log("需要回显的数据",data);
        console.log(data.name);
        //动态请求成功数据后，回显到页面上
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.parentCid = data.data.parentCid;
        this.category.catLevel = data.data.catLevel;
        this.category.showStatus = data.data.showStatus;
        this.category.sort = data.data.sort;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        
      });

     
    },
     //修改三级分类的信息
    editCategory(){
        var {catId,name,icon,productUnit} = this.category;
        // var data = {catId,name,icon,productUnit};

        this.$http({
          url: this.$http.adornUrl('/product/category/update'),
          method: 'post',
          data: this.$http.adornData({catId,name,icon,productUnit}, false)
        }).then(({ data }) => {
            this.$message({
              message:"菜单修改成功",
              type:"success"
            });

          // 刷新菜单
          this.getMenus();
          //设置需要默认开启的菜单
          this.expandedKey = [this.category.parentCid];
          this.dialogVisible = false;
        })
    },
    //3.删除子菜单的信息
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm(`是否确认删除【${data.name}】菜单？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          console.log("删除成功...");
          this.getMenus();
          this.expandedKey = [node.parent.data.catId];
          console.log("删除的对象数据", this.expandedKey);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })

    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
        console.log('handleDrop: ', draggingNode,dropNode, dropType);

        //1.当前节点的父节点id
         let pCid = 0;

         let sibling = [];

         if(dropType == "before" || dropType == "after") {
          pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
          sibling = dropNode.parent.childNodes;
         }else{
          pCid = dropNode.data.catId;
          sibling = dropNode.childNodes;
         }

        //2.当前拖动节点的最新顺序
        
        for(let i = 0; i < sibling.length; i++) {
            if(sibling[i].data.catId == draggingNode.data.catId){
              //如果遍历的是当前正在拖拽的节点
              let  catLevel = draggingNode.level;
              if(sibling[i].level != draggingNode.level) {
                 //当前节点的层级发生变化 
                 catLevel = sibling[i].level;
                //修改他子节点的层级
                this.updateChildNodeLevel(sibling[i])
             }
             this.updateNode.push({catId:sibling[i].data.catId,sort:i,parentCid:pCid,catLevel:catLevel})
            }else{
              //兄弟节点 只用修改顺序
              this.updateNode.push({catId:sibling[i].data.catId,sort:i})
            }
        }
        //3.当前拖动节点的最新层级
        console.log("updateNodes",this.updateNode);
     },
     updateChildNodeLevel(node) {
        if(node.childNodes.length>0){
          for(let i = 0; i < node.childNodes.length; i++) {
             var cNode = node.childNodes[i].data;
             this.updateNode.push({catId:cNode.catId,catLevel:node.childNodes[i].level})
            //  开始递归
            this.updateChildNodeLevel(node.childNodes[i]);
          }
        }
     },
       //拖拽数据
    allowDrop(draggingNode, dropNode, type) {        
      //1.被拖动的当前节点以及所在的父节点总层数不能大于3
      console.log("allowDrag:",draggingNode,dropNode,type);
      //1)被拖动的当前节点总层数
    
      this.countNodeLevel(draggingNode.data);

      //当前正在拖动的节点+ 父节点所在的深度不大于3即可

      // 深度差 + 1 = 层级
      //层级 =  子节点的level  - 当前节点的level + 1 
      let deep = (this.maxLevel - draggingNode.data.catLevel) + 1;
      console.log("深度： " ,this.maxLevel);
      //this.maxLevel
      if(type == "inner"){
        return (deep+dropNode.level) <= 3;
      }else{
        return (deep+dropNode.parent.level) <= 3;
      }


      // return false;
    },
    //统计总层数
    countNodeLevel(node){
      //找到所有子节点，求出最大深度
      if(node.children !=null && node.children.length >0){
          for(let i=0;i<node.children.length;i++){
             if(node.children[i].catLevel  > this.maxLevel){
                this.maxLevel = node.children[i].catLevel;
             }

             //递归 当前调用的子节点还有没有 子节点
             this.countNodeLevel(node.children[i])
          }
      }
    },




  },
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>